public class Solution { /** * @param s: The first string * @param b: The second string * @return true or false */ public boolean anagram(String s, String t) { // write your code here int result = 0; if(s.length() != t.length()) return false; for(int i = 0; i < s.length(); i++) { result ^= s.charAt(i); result ^= t.charAt(i); } if(result == 0) return true; return false; } };
Check if the String is unique.
这题也是比较高频的。其实可以直接用HashTable直接记下每一个字母出现的字数,如果有字母已经出现了,那么就返回false即可。当然,面试的时候follow up可能会要求你不要用extra data structure. 那么HashTable就不可以用了。 我们可以用一个int数组来解决一个问题。还是和上题一样,用一个256位的数组储存每一个字母出现的次数,如果发现改字母的数据已经不是0了,就可以返回false了。
####code[java]
1 2 3 4 5 6 7 8 9 10 11 12
public static boolean isUniqueNoExtraDataStructure(String testStr){ int alphabetInt = 0; String str = testStr.toLowerCase(); for (int i = 0; i < str.length(); i++){ int val = str.charAt(i) - 'a'; if ((alphabetInt & (1 << val)) > 0){ return false; } alphabetInt |= (1 << val); } return true; }
public static boolean compareUnique(String a) { boolean result = true; for(int i = 0; i < a.length(); i++) { if (a.indexOf(a.charAt(i)) != a.lastIndexOf(a.charAt(i))) { result = false; break; } } return result; }
public static void main(String[] args) { String str = "much. very you love I"; System.out.println(reverse(str));
}
public static String reverse(String s) { int pos = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') { pos = 0; } sb.insert(pos, c); if (c != ' ') { pos++; } } return sb.toString(); }
Array
basci skill
Reverse a array in java. 比较会常用的一种,记一下。当然也可以用库函数:Collections.reverse(Arrays.asList(nums));
1 2 3 4 5 6 7 8 9 10
public void reverse(int[] nums, int left, int right){ while(left<right){ int temp = nums[left]; nums[left]=nums[right]; nums[right]=temp; left++; right--; } }